
from flask import (
    Blueprint,
    request,
    g,
    redirect,
    url_for
)

from exit import db
from decimal import Decimal
from datetime import datetime, date, timedelta
from apps.api.decorators import login_required, login_need
from .forms import *
from .decorators import *
from apps.api.forms import UploadImgForm
from .models import *
from apps.api.models import *
from apps.common.models import *
from utils import restful, api_util, common_util, deliver_api
from sqlalchemy import func, or_
import requests
import json
from shortuuid import uuid


bp = Blueprint("mall", __name__, url_prefix="/mall")


@bp.route('/goods_index/')  # 商品首页
@login_need
def goods_index():
    name = request.args.get('name')
    banner_list = list()
    banner = Banner.query.order_by(Banner.priority).all()
    for i in banner:  # 轮播
        banner_info = i.banner_json()
        banner_list.append(banner_info)

    filters = list()
    filters.append(Goods.status == 0)
    if name:
        filters.append(or_(Goods.name.like('%' + name + '%'), Goods.goods_code.like('%' + name + '%')))
    goods = Goods.query.filter(*filters).order_by(Goods.priority).all()
    goods_list = list()
    for i in goods:
        goods_info = i.goods_json()

        time_required = api_util.trade_time_required(0)
        time_required2 = api_util.trade_time_required(5)
        if time_required is False and time_required2 is False:
            goods_info['high'] = '--'
            goods_info['low'] = '--'
            goods_info['buy'] = '--'
            goods_info['sell'] = '--'
        elif i.goods_code != '202010':
            goods_info['high'] = '--'
            goods_info['low'] = '--'
            goods_info['buy'] = '--'
            goods_info['sell'] = '--'
        else:
            goods_info['high'] = '%.2f' % (i.price * Decimal('1.02'))
            goods_info['low'] = '%.2f' % (i.price * Decimal('0.98'))
            # buy_sell = db.session.query(func.sum(BuyDeal.deal_money)).filter(
            #     BuyDeal.goods_id == i.id, BuyDeal.create_time >= date.today(), BuyDeal.deal_type != 3
            # ).scalar()
            # buy_sell = buy_sell or 0
            buy_sell = Decimal(redis_cach.get('buy_sell_price'))
            # buy_sell_num = redis_cach.get('buy_sell_num')
            goods_info['buy'] = buy_sell
            goods_info['sell'] = buy_sell

        goods_list.append(goods_info)
    index_dict = dict()
    index_dict['banner_list'] = banner_list
    index_dict['goods_list'] = goods_list
    return restful.success(data=index_dict)


@bp.route('/goods_detail/', methods=['POST'])   # 商品详情页
@login_required
def goods_detail():
    # time_required = api_util.trade_time_required(0)
    # if time_required is False:
    #     return restful.params_error(message='当前时间未开放！')
    form = DetailForm(request.form)
    if form.validate():
        goods_id = form.goods_id.data
        # token = form.token.data
        goods = Goods.query.filter_by(id=goods_id, is_show=0).first()
        # print(goods_id)
        if goods is None:
            return restful.params_error(message='未找到商品,请刷新后重试！')

        # details = GoodsDetail.query.filter_by(goods_id=goods.id).order_by(GoodsDetail.priority).all()
        banner_list = list()
        detail_list = list()

        # for i in details:
        #     detail_json = i.goods_detail_json()
        #     if i.status == 0:
        #         banner_list.append(detail_json)
        #     else:
        #         detail_list.append(detail_json)

        # buy_order = BuyOrder.query.filter_by(t_type=1, status=0).order_by(BuyOrder.price.desc()).limit(5)
        # buy_list = list()
        # for i in buy_order:
        #     order_info = i.buy_order_json()
        #     buy_list.append(order_info)
        #
        # sell_list = list()
        # sell_order = BuyOrder.query.filter_by(t_type=2, status=0).order_by(BuyOrder.price).limit(5)
        # for j in sell_order:
        #     order_info = j.buy_order_json()
        #     sell_list.append(order_info)

        get_buy_list = redis_cach.cache.lrange('buy_list', 0, -1)
        get_sell_list = redis_cach.cache.lrange('sell_list', 0, -1)
        get_buy_list = [eval(i) for i in get_buy_list]
        get_sell_list = [eval(i) for i in get_sell_list]

        goods_info = goods.goods_json()
        goods_info['banner_list'] = banner_list
        goods_info['detail_list'] = detail_list
        # goods_info['buy_list'] = buy_list
        # goods_info['sell_list'] = sell_list

        goods_info['buy_list'] = get_buy_list
        goods_info['sell_list'] = get_sell_list

        # 上面6个数据
        # buy_sell = db.session.query(func.sum(BuyDeal.deal_money)).filter(
        #     BuyDeal.goods_id == goods.id, BuyDeal.create_time >= date.today(), BuyDeal.deal_type != 3
        # ).scalar()
        # buy_sell_price = buy_sell or 0

        # buy_sell_num = db.session.query(func.sum(BuyDeal.deal_num)).filter(
        #     BuyDeal.goods_id == goods.id, BuyDeal.create_time >= date.today(), BuyDeal.deal_type != 3
        # ).scalar()
        # buy_sell_num = buy_sell_num or 0
        buy_sell_price = Decimal(redis_cach.get('buy_sell_price'))
        buy_sell_num = Decimal(redis_cach.get('buy_sell_num'))

        y_open = 0
        history_price = HistoryPrice.query.order_by(HistoryPrice.create_time.desc()).first()
        if history_price:
            y_open = history_price.y_price

        goods_info['t_open'] = goods.price      # 今开
        goods_info['y_open'] = y_open      # 昨收
        goods_info['high'] = '%.2f' % (goods.price * Decimal('1.02'))        # 最高
        goods_info['low'] = '%.2f' % (goods.price * Decimal('0.98'))         # 最低
        global_price = GlobalParams.get_params(7)
        global_num = GlobalParams.get_params(6)
        goods_info['buy_sell_price'] = Decimal(buy_sell_price * 2) + global_price  # 金额
        goods_info['buy_sell_num'] = Decimal(buy_sell_num) + global_num      # 数量

        goods_info['collect'] = 0  # 收藏
        user_collect = UserCollect.query.filter_by(user_id=g.user.id, goods_id=goods.id).first()
        if user_collect:
            goods_info['collect'] = 1
        goods_info['buy_start'] = '%.2f' % (goods.price * Decimal('0.98'))
        goods_info['buy_end'] = '%.2f' % (goods.price * Decimal('1.02'))
        goods_info['sell_start'] = '%.2f' % (goods.price * Decimal('0.98'))
        goods_info['sell_end'] = '%.2f' % (goods.price * Decimal('1.02'))

        # 可用数量
        deal_num = db.session.query(func.sum(BuyDeal.s_num_sell)).filter(
            BuyDeal.goods_id == goods_id, BuyDeal.s_num_sell > 0,
            BuyDeal.buyer_id == g.user.id
        ).scalar()

        # 冻结数量
        freeze_num = db.session.query(func.sum(BuyDeal.s_num - BuyDeal.s_num_sell)).filter(
            BuyDeal.goods_id == goods_id, BuyDeal.s_num > 0,
            BuyDeal.buyer_id == g.user.id, BuyDeal.t_type == 1,
            BuyDeal.status == 0
        ).scalar()
    
        # 待释放数量
        release_num = db.session.query(func.sum(BuyDeal.s_num - BuyDeal.s_num_sell)).filter(
            BuyDeal.goods_id == goods_id, BuyDeal.s_num > 0,
            BuyDeal.buyer_id == g.user.id, BuyDeal.t_type == 2
        ).scalar()

        # 交易额
        # trade_price = db.session.query(func.sum(BuyDeal.deal_money)).filter(
        #     BuyDeal.goods_id == goods_id, BuyDeal.deal_type == 1,
        #     or_(BuyDeal.buyer_id == g.user.id, BuyDeal.seller_id == g.user.id)
        # ).scalar()
        # trade_price = trade_price or 0
        # sql = "SELECT ifnull(SUM(deal_money),0) as deal_money from c_mall_buy_deal_h where (buyer_id='{}' or seller_id='{}') and deal_type=1 and sell_order_id is not null;".format(g.user.id, g.user.id)
        #
        # trade_price_obj = db.session.execute(sql).first()
        # if trade_price_obj:
        #     trade_price += trade_price_obj.deal_money

        deal_num = deal_num or 0
        freeze_num = freeze_num or 0
        release_num = release_num or 0

        goods_info['deal_num'] = deal_num
        goods_info['freeze_num'] = freeze_num
        goods_info['release_num'] = release_num
        goods_info['trade_price'] = g.user.total_deal_money

        return restful.success(data=goods_info)
    else:
        return restful.params_error(message=form.get_error())


@bp.route('/buyer_order/', methods=['POST'])     # 挂买订单
@login_required
def buyer_order():
    if g.user.status != 2:
        return restful.params_error(message='未实名不能交易')
    time_required = api_util.trade_time_required(0)
    time_required2 = api_util.trade_time_required(5)
    if time_required is False and time_required2 is False:
        return restful.params_error(message='当前时间未开放！')
    try:
        form = BuyForm(request.form)
        if form.validate():
            goods_id = form.goods_id.data
            num = form.num.data
            price = form.price.data
            # t_type = form.t_type.data
            if g.user.today_buy_num < 0:
                return restful.params_error(message='挂单数量超出限制！')
            if g.user.buy_num < 10:

                # buy_order_num = db.session.query(func.sum(BuyOrder.num)).filter(
                #     BuyOrder.create_time >= date.today(),
                #     BuyOrder.user_id == g.user.id,
                #     BuyOrder.t_type == 1,
                #     BuyOrder.status != 2,
                #     BuyOrder.status != 3,
                # ).scalar()
                # buy_order_num = buy_order_num or 0
                global_buy_1 = int(GlobalParams.get_params(2))
                global_buy_2 = int(GlobalParams.get_params(3))
                if num + g.user.today_buy_num > global_buy_1:
                    return restful.params_error(message='每日挂买数量不能超过{}个'.format(global_buy_1))
                if num > global_buy_2:
                    return restful.params_error(message='每单挂买数量不能超过{}个'.format(global_buy_2))

            goods = Goods.query.filter_by(id=goods_id).first()
            if goods is None:
                return restful.params_error(message='未找到拍品')
            if price < Decimal('%.2f' % (goods.price * Decimal('0.98'))):
                return restful.params_error(message='价格不规范')

            total_price = Decimal(num * price)
            # 买入手续费
            global_params = GlobalParams.get_params(1)
            buy_fee = total_price * global_params

            if g.user.income < (total_price + buy_fee):
                return restful.params_error(message='余额不足')

            g.user.income -= total_price
            api_util.user_record(user_id=g.user.id, r_label=1, r_type=3, r_state=2, num=total_price, r_wallet=1)

            g.user.income -= buy_fee
            api_util.user_record(user_id=g.user.id, r_label=2, r_type=1, r_state=2, num=buy_fee, r_wallet=1)

            g.user.today_buy_num += num

            create_order = BuyOrder(
                user_id=g.user.id, goods_id=goods.id, is_show=0, status=0,
                t_type=1, num=num, price=price, total_price=total_price,
                surplus_num=num,  surplus_price=total_price, total_fee=buy_fee,
                surplus_fee=buy_fee, deal_priority=g.user.deal_priority
            )
            db.session.add(create_order)
            db.session.commit()
            return restful.success()
        else:
            return restful.params_error(message=form.get_error())
    except Exception as e:
        print(e)
        db.session.close()
        return restful.params_error(message='网络错误请重试！')


@bp.route('/seller_order/', methods=['POST'])     # 挂卖订单
@login_required
def seller_order():
    if g.user.status != 2:
        return restful.params_error(message='未实名不能交易')
    time_required = api_util.trade_time_required(0)
    time_required2 = api_util.trade_time_required(5)
    if time_required is False and time_required2 is False:
        return restful.params_error(message='当前时间未开放！')
    try:
        form = SellForm(request.form)
        if form.validate():
            bath_id = form.bath_id.data
            num = form.num.data
            price = form.price.data
            # t_type = form.t_type.data

            if g.user.today_sell_num < 0:
                return restful.params_error(message='挂单数量超出限制！')
            if g.user.buy_num < 10:
                #
                # buy_order_count = BuyOrder.query.filter(
                #     BuyOrder.user_id == g.user.id,
                #     BuyOrder.t_type == 2,
                #     BuyOrder.status != 2,
                #     BuyOrder.status != 3,
                #     BuyOrder.create_time >= date.today()
                # ).count()

                buy_first = BuyOrder.query.filter(
                    BuyOrder.user_id == g.user.id,
                    BuyOrder.t_type == 2,
                    BuyOrder.create_time >= date.today()
                ).order_by(BuyOrder.create_time.desc()).first()

                if buy_first:
                    now = datetime.now()
                    second = (now - buy_first.create_time).seconds
                    if second < 30:
                        return restful.params_error(message='每单需间隔30秒')

                global_buy_1 = int(GlobalParams.get_params(4))
                global_buy_2 = int(GlobalParams.get_params(5))

                if num + g.user.today_sell_num > global_buy_1:
                    return restful.params_error(message='每日挂卖单不能超过{}单'.format(global_buy_1))

                if num > global_buy_2:
                    return restful.params_error(message='每单挂卖数量不能超过{}个'.format(global_buy_2))

            buy_deal = BuyDeal.query.filter_by(id=bath_id, buyer_id=g.user.id).first()
            if buy_deal is None:
                return restful.params_error(message='未找到可卖批次')
            if buy_deal.tn_day != 0:
                return restful.params_error(message='该批次下个交易日可交易！')
            if buy_deal.s_num_sell < num:
                return restful.params_error(message='剩余可卖数量不足')
            goods = Goods.query.filter_by(id=buy_deal.goods_id).first()
            if price < Decimal('%.2f' % (goods.price * Decimal('0.98'))):
                return restful.params_error(message='价格不规范')

            buy_deal.s_num_sell -= num
            buy_deal.s_num -= num

            total_price = num * price

            g.user.today_sell_num += num

            # buyer_orders = BuyOrder.query.filter_by(id=buy_deal.sell_order_id).first()
            create_order = BuyOrder(
                user_id=g.user.id, goods_id=buy_deal.goods_id, is_show=0, status=0,
                t_type=2, num=num, price=price, total_price=total_price,
                surplus_num=num,  surplus_price=total_price,
                sell_batch_id=buy_deal.id, surplus_fee=0,
                deal_priority=g.user.deal_priority
            )
            db.session.add(create_order)
            db.session.commit()
            return restful.success()
        else:
            return restful.params_error(message=form.get_error())
    except Exception as e:
        print(e)
        db.session.close()
        return restful.params_error(message='网络错误请重试！')


@bp.route('/sell_bath/')    # 可卖批次
@login_required
def sell_bath():
    page = request.args.get('page', default=1, type=int)
    pages = (page - 1) * 20
    bath = BuyDeal.query.filter(
        BuyDeal.buyer_id == g.user.id, BuyDeal.s_num_sell > 0, BuyDeal.status == 0
    ).order_by(BuyDeal.create_time).limit(20).offset(pages)
    bath_list = list()
    for i in bath:
        bath_info = i.buy_deal_json()
        if i.tn_day != 0:
            bath_info['s_num_sell'] = 0
        # if i.deal_price == 800:
        #    status_str = '释放票'
        if i.t_type == 1:
            status_str = '释放票'
        else:
            status_str = '剩余数量'
        bath_info['status_str'] = status_str
        bath_list.append(bath_info)

    data_dict = dict()
    data_dict['bath_list'] = bath_list
    return restful.success(data=data_dict)


@bp.route('/del_buy_order/', methods=['POST'])  # 取消订单
@login_required
def del_buy_order():
    time_required = api_util.trade_time_required(0)
    time_required2 = api_util.trade_time_required(5)
    if time_required is False and time_required2 is False:
        return restful.params_error(message='当前时间未开放！')
    order_id = request.form.get('order_id')
    buy_order = BuyOrder.query.filter_by(id=order_id, user_id=g.user.id, status=0).with_for_update().first()
    if buy_order is None:
        return restful.params_error(message='未找到订单')

    buy_order.status = 2
    if buy_order.t_type == 2:   # 返还批次数量
        buy_order.bath.s_num_sell += buy_order.surplus_num
        buy_order.bath.s_num += buy_order.surplus_num
        g.user.today_sell_num -= buy_order.surplus_num
    elif buy_order.t_type == 1:
        g.user.income += buy_order.surplus_price
        api_util.user_record(user_id=g.user.id, r_label=1, r_type=4, r_state=1, num=buy_order.surplus_price, r_wallet=1)
        g.user.today_buy_num -= buy_order.surplus_num
        g.user.income += buy_order.surplus_fee
        api_util.user_record(user_id=g.user.id, r_label=2, r_type=3, r_state=1, num=buy_order.surplus_fee, r_wallet=1)
    db.session.commit()
    return restful.success()


@bp.route('/buy_order_record/', methods=['POST'])     # 历史购买订单
@login_required
def buy_order_record():
    form = OrderHistoryForm(request.form)
    if form.validate():
        page = form.page.data
        t_type = form.t_type.data
        pages = (page - 1) * 20

        if t_type == 0:
            buy_order_obj = BuyOrder.query.filter(
                BuyOrder.user_id == g.user.id,
                # BuyOrder.is_show == 0,
            )
        else:
            buy_order_obj = BuyOrder.query.filter(
                BuyOrder.user_id == g.user.id,
                # BuyOrder.is_show == 0,
                BuyOrder.t_type == t_type,
            )

        buy_order = buy_order_obj.order_by(BuyOrder.create_time.desc()).limit(
                20).offset(pages)
        order_list = list()

        for i in buy_order:
            order_json = i.buy_order_json()
            # goods_list = list()
            goods = Goods.query.filter_by(id=i.goods_id).first()
            if goods:
                order_json['name'] = goods.name
                order_json['goods_code'] = goods.goods_code

            order_list.append(order_json)

        order_dict = dict()
        order_dict['order_list'] = order_list
        return restful.success(data=order_dict)
    else:
        return restful.params_error(message=form.get_error())


@bp.route('/deliver_info/', methods=['POST'])     # 快递信息
@login_required
def deliver_info():
    order_id = request.form.get('order_id')
    buy_order = BuyOrder.query.filter_by(id=order_id, user_id=g.user.id).first()
    if buy_order is None:
        return restful.params_error(message='未找到订单')
    # if buy_order.logistics_num is None:
    #     get_data = []
    # else:
    #     get_data = deliver_api.cache_deliver(buy_order.logistics_simple, buy_order.logistics_num)

    deliver_dict = dict()
    deliver_dict['logistics_num'] = buy_order.logistics_num
    deliver_dict['logistics_name'] = buy_order.logistics_name
    # deliver_dict['context_list'] = get_data
    deliver_dict['context_list'] = []
    return restful.success(data=deliver_dict)


@bp.route('/confirm_order/', methods=['POST'])      # 确认收货
@login_required
def confirm_order():
    order_id = request.form.get('order_id')
    buy_order = BuyOrder.query.filter_by(id=order_id, user_id=g.user.id, status=2).first()
    if buy_order is None:
        return restful.params_error(message='未找到订单')
    buy_order.status = 3
    buy_order.update_time3 = datetime.now()
    db.session.commit()
    return restful.success()


@bp.route('/collect_goods/', methods=['POST'])  # 收藏
@login_required
def collect_goods():
    goods_id = request.form.get('goods_id')
    goods = Goods.query.filter_by(id=goods_id).first()
    if goods is None:
        return restful.params_error(message='未找到作品')
    collects = UserCollect.query.filter_by(user_id=g.user.id, goods_id=goods.id).first()
    if collects:
        db.session.delete(collects)
    else:
        create_collect = UserCollect(
            user_id=g.user.id, goods_id=goods.id,
            name=goods.name, goods_code=goods.goods_code
        )
        db.session.add(create_collect)
    db.session.commit()
    return restful.success()


@bp.route('/order_hall/', methods=['POST'])   # 订单大厅
@login_required
def order_hall():
    if g.user.open_status != 1:
        return restful.success(data={'order_list': []})
    page = request.form.get('page', type=int, default=1)
    pages = (page - 1) * 10
    t_type = request.form.get('t_type')
    buy_order = BuyOrder.query.filter(
        BuyOrder.t_type == t_type,
        BuyOrder.status == 0,
        BuyOrder.user_id != g.user.id
    ).order_by(BuyOrder.create_time.desc()).limit(10).offset(pages)
    order_list = list()
    for i in buy_order:
        order_info = i.buy_order_json()

        goods = Goods.query.filter_by(id=i.goods_id).first()
        if goods:
            order_info['name'] = goods.name
            order_info['goods_code'] = goods.goods_code
        order_list.append(order_info)

    data_dict = dict()
    data_dict['order_list'] = order_list
    return restful.success(data=data_dict)


@bp.route('/deal_buy/', methods=['POST'])   # 交易买
@login_required
def deal_buy():
    time_required = api_util.trade_time_required(0)
    time_required2 = api_util.trade_time_required(5)
    if time_required is False and time_required2 is False:
        return restful.params_error(message='当前时间未开放！')
    try:
        if g.user.open_status != 1:
            return restful.params_error(message='未开通点对点')
        order_id = request.form.get('order_id')
        buy_order = BuyOrder.query.filter_by(id=order_id, status=0, t_type=2).with_for_update().first()
        if buy_order is None:
            return restful.params_error(message='未找到订单')
        num = request.form.get('num', type=int)
        if num < 0:
            return restful.params_error(message='数量格式错误')

        if buy_order.surplus_num < num:
            return restful.params_error(message='订单数量不足')

        if g.user.buy_num < 10:
            buy_deal_num = db.session.query(func.sum(BuyDeal.deal_num)).filter(
                BuyDeal.buyer_id == g.user.id,
                BuyDeal.create_time >= date.today(),
            ).scalar()
            buy_deal_num = buy_deal_num or 0

            global_buy_1 = int(GlobalParams.get_params(2))
            if buy_deal_num + num > global_buy_1:
                return restful.params_error(message='每日交易只能购买{}个'.format(global_buy_1))

            global_buy_2 = int(GlobalParams.get_params(3))

            if num > global_buy_2:
                return restful.params_error(message='每单挂买数量不能超过{}个'.format(global_buy_2))

        total_price = Decimal(num * buy_order.price)
        # 买入手续费
        global_params = GlobalParams.get_params(1)
        buy_fee = total_price * global_params

        if g.user.income < (total_price + buy_fee):
            return restful.params_error(message='可用资产不足')

        # 买家买入
        g.user.income -= total_price
        g.user.today_buy_num += num
        api_util.user_record(user_id=g.user.id, r_label=1, r_type=1, r_state=2, num=total_price, r_wallet=1, status=0)
        g.user.deal_buy_num += num      # 买入数量
        # 买入手续费
        g.user.income -= buy_fee
        api_util.user_record(user_id=g.user.id, r_label=2, r_type=1, r_state=2, num=total_price, r_wallet=1)

        # 卖家卖出
        seller = User.query.filter_by(id=buy_order.user_id).first()
        seller.deal_sell_num += num

        # 卖出手续费
        global_params_sell = GlobalParams.get_params(0)
        sell_fee = total_price * global_params_sell

        seller.income += (total_price - sell_fee)
        api_util.user_record(user_id=g.user.id, r_label=3, r_type=1, r_state=1, num=total_price, r_wallet=1)
        # 卖出手续费记录
        api_util.user_record(user_id=g.user.id, r_label=2, r_type=2, r_state=2, num=sell_fee, r_wallet=1)

        buy_order.surplus_num -= num
        if buy_order.surplus_num == 0:
            buy_order.status = 1

        create_deal = BuyDeal(
            sell_order_id=buy_order.id, buyer_id=g.user.id, seller_id=buy_order.user_id,
            sell_batch_id=buy_order.bath.id, deal_num=num, deal_price=buy_order.price,
            deal_type=2, deal_money=total_price, s_num=num, s_num_sell=num, tn_day=1,
            goods_id=buy_order.goods_id, buy_fee=buy_fee, sell_fee=sell_fee
        )
        db.session.add(create_deal)
        db.session.commit()
        return restful.success()
    except Exception as e:
        print(e)
        db.session.close()
        return restful.params_error(message='网络错误请重试！')


@bp.route('/deal_sell/', methods=['POST'])   # 交易卖
@login_required
def deal_sell():
    time_required = api_util.trade_time_required(0)
    time_required2 = api_util.trade_time_required(5)
    if time_required is False and time_required2 is False:
        return restful.params_error(message='当前时间未开放！')
    try:
        if g.user.open_status != 1:
            return restful.params_error(message='未开通点对点')
        order_id = request.form.get('order_id')
        buy_order = BuyOrder.query.filter_by(id=order_id, status=0, t_type=1).with_for_update().first()
        if buy_order is None:
            return restful.params_error(message='未找到订单')
        num = request.form.get('num', type=int)
        if num < 0:
            return restful.params_error(message='数量格式错误')

        if buy_order.surplus_num < num:
            return restful.params_error(message='订单数量不足')

        if g.user.buy_num < 10:
            buy_deal_num = db.session.query(func.sum(BuyDeal.deal_num)).filter(
                BuyDeal.seller_id == g.user.id,
                BuyDeal.create_time >= date.today(),
            ).scalar()
            buy_deal_num = buy_deal_num or 0

            global_buy_1 = int(GlobalParams.get_params(4))
            if buy_deal_num + num > global_buy_1:
                return restful.params_error(message='每日交易只能卖出{}个'.format(global_buy_1))
            global_buy_2 = int(GlobalParams.get_params(5))
            if num > global_buy_2:
                return restful.params_error(message='每单挂卖数量不能超过{}个'.format(global_buy_2))

        bath_id = request.form.get('bath_id')
        buy_deal = BuyDeal.query.filter(BuyDeal.id == bath_id, BuyDeal.buyer_id == g.user.id, BuyDeal.s_num_sell >= num).first()
        if buy_deal is None:
            return restful.params_error(message='该订单不符合交易')

        buy_deal.s_num_sell -= num
        buy_deal.s_num -= num

        # 卖出
        total_price = Decimal(num * buy_order.price)
        # 卖出手续费
        global_params_sell = GlobalParams.get_params(0)
        sell_fee = total_price * global_params_sell
        # 加收益
        g.user.income += (total_price - sell_fee)
        g.user.today_sell_num += num
        api_util.user_record(user_id=g.user.id, r_label=3, r_type=1, r_state=1, num=total_price, r_wallet=1)
        # 卖出手续费记录
        api_util.user_record(user_id=g.user.id, r_label=2, r_type=2, r_state=2, num=sell_fee, r_wallet=1)

        # 买方手续费
        global_params = GlobalParams.get_params(1)
        buy_fee = total_price * global_params
        # 减去剩余的
        buy_order.surplus_price -= total_price
        buy_order.surplus_fee -= buy_fee
        buyer = User.query.filter_by(id=buy_order.user_id).first()

        buy_order.surplus_num -= num
        if buy_order.surplus_num == 0:
            buy_order.status = 1
            # 返还剩余手续费
            if buy_order.surplus_price > 0:
                buyer.income += buy_order.surplus_price
                api_util.user_record(user_id=buyer.id, r_label=1, r_type=4, r_state=1, num=buy_order.surplus_price, r_wallet=1)

                buyer.income += buy_order.surplus_fee
                api_util.user_record(user_id=buyer.id, r_label=2, r_type=3, r_state=1, num=buy_order.surplus_fee, r_wallet=1)

        create_deal = BuyDeal(
            sell_order_id=buy_order.id, buyer_id=buy_order.user_id, seller_id=g.user.id,
            sell_batch_id=buy_deal.id, deal_num=num, deal_price=buy_order.price,
            deal_type=2, deal_money=total_price, s_num=num, s_num_sell=num, tn_day=1,
            goods_id=buy_order.goods_id, buy_fee=buy_fee, sell_fee=sell_fee
        )
        db.session.add(create_deal)
        db.session.commit()
        return restful.success()
    except Exception as e:
        print(e)
        db.session.close()
        return restful.params_error(message='网络错误请重试！')


@bp.route('/buy_deal_record/')      # 所有交易批次
@login_required
def buy_deal_record():
    page = request.args.get('page', type=int, default=1)
    pages = (page - 1) * 10
    buy_deal = BuyDeal.query.filter(BuyDeal.buyer_id == g.user.id, BuyDeal.s_num > 0).order_by(BuyDeal.create_time.desc()).limit(10).offset(pages)
    deal_list = list()
    for i in buy_deal:
        deal_info = i.buy_deal_json()
        deal_info['total_price'] = i.deal_price * i.s_num_sell
        goods = Goods.query.filter_by(id=i.goods_id).first()
        if goods:
            deal_info['name'] = goods.name
            deal_info['goods_code'] = goods.goods_code
        deal_list.append(deal_info)

    data_dict = dict()
    data_dict['deal_list'] = deal_list
    return restful.success(data=data_dict)


@bp.route('/pick_up/', methods=['POST'])      # 提货
@login_required
def pick_up():
    bath_id = request.form.get('bath_id')
    num = request.form.get('num', type=int)
    sh_name = request.form.get('sh_name')
    sh_phone = request.form.get('sh_phone')
    sh_province = request.form.get('sh_province')
    sh_city = request.form.get('sh_city')
    sh_district = request.form.get('sh_district')
    sh_place = request.form.get('sh_place')

    if num < 0:
        return restful.params_error(message='数量格式错误')
    buy_deal = BuyDeal.query.filter_by(id=bath_id, buyer_id=g.user.id).first()
    if buy_deal is None:
        return restful.params_error(message='未找到订单')
    if num > buy_deal.s_num:
        return restful.params_error(message='数量不足')
    if buy_deal.s_num_sell == buy_deal.s_num:
        buy_deal.s_num_sell -= num

    buy_deal.s_num -= num

    # 减去额度
    # g.user.income_r -= (num * buy_deal.deal_price)
    # if g.user.income_r < 0:
    #     g.user.income_r = 0

    buy_deal_deliver = BuyDealDeliver(
        sell_batch_id=buy_deal.id, num=num, price=buy_deal.deal_price,
        total_price=buy_deal.deal_price * num, sh_name=sh_name,
        sh_phone=sh_phone, sh_province=sh_province, sh_city=sh_city,
        sh_district=sh_district, sh_place=sh_place, user_id=g.user.id,
        goods_id=buy_deal.goods_id
    )
    db.session.add(buy_deal_deliver)
    db.session.commit()
    return restful.success()


@bp.route('/deal_deliver_record/')      # 提货列表
@login_required
def deal_deliver_record():
    page = request.form.get('page', type=int, default=1)
    pages = (page - 1) * 20
    deal_deliver = BuyDealDeliver.query.filter_by(user_id=g.user.id, status=0).order_by(BuyDealDeliver.create_time.desc()).limit(20).offset(pages)
    deliver_list = list()
    for i in deal_deliver:
        deliver = i.buy_deal_deliver_json()
        deliver['price'] = 0
        deliver['total_price'] = 0
        # buy_deal = BuyDeal.query.filter_by(id=i.sell_batch_id).first()
        goods = Goods.query.filter_by(id=i.goods_id).first()
        if goods:
            deliver['name'] = goods.name
            deliver['goods_code'] = goods.goods_code
        deliver_list.append(deliver)

    data_dict = dict()
    data_dict['deliver_list'] = deliver_list
    return restful.success(data=data_dict)
